<?php

namespace App\Http\Controllers\Api\Backstage;

use App\Models\QuestionsAnswers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class QuestionsController extends Controller
{
    public function index()
    {
        $data['questionsList'] = QuestionsAnswers::paginate(20);
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'qaId' => 'integer|required',
            'question' => 'required',
            'answers' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $data['createTime'] = date("Y-m-d H:i:s");
        $qaId = @$data['qaId'];
        unset($data['qaId']);

        if ($qaId){
            $status = QuestionsAnswers::where('qaId', $qaId)->update($data);
            if (!$status) {
                return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
            }
        }else{
            $status = QuestionsAnswers::create($data);

            if (!$status) {
                return $this->apiResponse('', config('errorCode.INSERT_REQ_FAILED'));
            }

        }
        return $this->apiResponse(true);

    }

    public function show($qaId)
    {
        $data = QuestionsAnswers::find($qaId);
        return $this->apiResponse($data);
    }

    public function destroy($qaId)
    {
        $data = QuestionsAnswers::destroy($qaId);
        return $this->apiResponse($data);
    }
}
